<template>
  <div style="padding:10px 20px"  class="page-container">
    <!-- 顶级筛选 -->
    <div class="top-filter">
      <div class="search-container">
        <div class="search-input-wrapper">
          <input v-model="searchQuery" placeholder="搜索题目" class="search-input" />
          <img src="@/assets/picture/find.png" alt="搜索" class="search-icon" @click="searchQuestions" />
        </div>
      </div>
    </div>

    <!-- 二级筛选 -->
    <div class="secondary-filters">
      <!-- 方向筛选 -->
      <div class="filter-group">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">专业:</p>
        <span @click="toggleFilterDirection('all')" :class="{ 'active-filter': selectedFilterDirection === 'all' }">全部</span>
        <span v-for="direction in directions" :key="direction.direction_id" @click="toggleFilterDirection(direction.direction_id)" :class="{ 'active-filter': selectedFilterDirection === direction.direction_id }">
          {{ direction.direction_title }}
        </span>
      </div>

      <div class="filter-group" v-if="selectedFilterDirection !== 'all'">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">方向:</p>
        <span @click="toggleFilterPoint('all')" :class="{ 'active-filter': selectedFilterPoint === 'all' }">全部</span>
        <span v-for="point in directions.find(dir => dir.direction_id === selectedFilterDirection)?.points || []" :key="point.point_id" @click="toggleFilterPoint(point.point_id)" :class="{ 'active-filter': selectedFilterPoint === point.point_id }">
          {{ point.point_content }}
        </span>
      </div>

      <!-- 题型筛选 -->
      <div class="filter-group">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">题型:</p>
        <span @click="toggleFilterQuestionType('all')" :class="{ 'active-filter': selectedQuestionType === 'all' }">全部</span>
        <span @click="toggleFilterQuestionType('only_sel')" :class="{ 'active-filter': selectedQuestionType === 'only_sel' }">单选题</span>
        <span @click="toggleFilterQuestionType('many_sel')" :class="{ 'active-filter': selectedQuestionType === 'many_sel' }">多选题</span>
        <span @click="toggleFilterQuestionType('yesorno')" :class="{ 'active-filter': selectedQuestionType === 'yesorno' }">判断题</span>
        <span @click="toggleFilterQuestionType('qna')" :class="{ 'active-filter': selectedQuestionType === 'qna' }">简答题</span>
      </div>

      <!-- 难度筛选 -->
      <div class="filter-group">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">难度:</p>
        <span @click="toggleFilterDifficulty('all')" :class="{ 'active-filter': selectedDifficulty === 'all' }">全部</span>
        <span @click="toggleFilterDifficulty('0')" :class="{ 'active-filter': selectedDifficulty === '0' }">简单</span>
        <span @click="toggleFilterDifficulty('1')" :class="{ 'active-filter': selectedDifficulty === '1' }">中等</span>
        <span @click="toggleFilterDifficulty('2')" :class="{ 'active-filter': selectedDifficulty === '2' }">困难</span>
      </div>
    </div>

    <!-- 题目表格 -->
    <table class="question-table">
      <colgroup>
        <col style="width: 60%;" />
        <col style="width: 7%;" />
        <col style="width: 15%;" />
        <col style="width: 10%;" />
        <col style="width: 8%;" />
      </colgroup>
      <thead>
        <tr>
          <th>题目描述</th>
          <th>难度</th>
          <th>方向</th>
          <th>题型</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="question in paginatedData" :key="question.qs_id" class="table-row">
          <td>
            <details class="question-details">
              <summary style="cursor: pointer;">
                <span class="question-type" style="color:gray">[{{ getQuestionType(question.qs_type) }}]</span>
                <span>{{ question.qs_title.replace(/<[^>]*>?/gm, '') }}</span>
              </summary>
              <div class="question-options" style="margin-left:60px">
                <!-- 仅选择题类型显示选项 -->
                <div v-if="question.qs_type === 'only_sel' || question.qs_type === 'many_sel'">
                  <div v-for="(option, index) in question.options" :key="option.option_id" style="padding-bottom: 5px;">
                    {{ String.fromCharCode(65 + index) }}. {{ option.option_content }}
                    <span v-if="option.is_right" style="font-weight:bold;color:#4CAF50">√</span>
                  </div>
                </div>
                <!-- 判断题类型显示选项 -->
                <div v-if="question.qs_type === 'yesorno'" style="padding-bottom: 5px;">
                  <div v-for="(option, index) in question.options" :key="option.option_id" style="padding-bottom: 5px;">
                    {{ String.fromCharCode(65 + index) }}. {{ option.option_content }}
                    <span v-if="option.is_right" style="font-weight:bold;color:#4CAF50">√</span>
                  </div>
                </div>
                <!-- 简答题显示答案 -->
                <div v-if="question.qs_type === 'qna'" style="padding-top: 10px;">
                  <strong>答案:</strong>
                  <span v-html="question.right_ans"></span>
                </div>
              </div>
            </details>
          </td>
          <td>{{ getDifficultyLabel(question.difficulty) }}</td>
          <td>{{ question.point_content }}</td>
          <td class="action-cell">
            {{ getQuestionType(question.qs_type) }}题
          </td>
           <td class="action-cell">
              <div class="favorite-icon" @click.stop="toggleFavorite(question)">
                <img
                  :src="question.is_store ? require('@/assets/picture/star-solid.png') : require('@/assets/picture/star.png')"
                  :alt="question.is_store ? '已收藏' : '未收藏'"
                />
              </div>
            </td>
        </tr>

        <!-- 当无结果时显示提示 -->
        <tr v-if="paginatedData.length === 0">
          <td :colspan="4" class="no-results">没有找到匹配的题目。</td>
        </tr>
      </tbody>
    </table>

    <!-- 分页 -->
    <Pagination :current-page="currentPage" :total-pages="totalPages" @page-change="handlePageChange" />
  </div>
</template>

<script>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from 'element-plus';
import { getQuestionDirections, StufetchQuestions } from "@/services/api";
import Pagination from "@/components/PagiNation.vue";
import {   addQuestionFavorite, removeQuestionFavorites  } from '@/services/api';

export default {
  name: "QuestionBankPage",
  components: { Pagination },
  setup() {
    const userId = ref(localStorage.getItem('id')); 
    const questions = ref([]);
    const searchQuery = ref("");
    const selectedFilterDirection = ref("all");
    const selectedQuestionType = ref("all");
    const selectedDifficulty = ref("all");
    const directions = ref([]);
    const selectedFilterPoint = ref("all");

    const currentPage = ref(1);
    const pageSize = 10;

    // 获取方向列表
    const fetchDirections = async () => {
      try {
        const response = await getQuestionDirections();
        if (response.data.status === 1) {
          directions.value = response.data.data;
        } else {
          ElMessage.error("获取方向列表失败");
        }
      } catch (error) {
        console.error("Error fetching directions:", error);
        ElMessage.error("网络错误，无法获取方向列表");
      }
    };

    // 获取题目列表
    const fetchQuestionsData = async () => {
  try {
    const qsTypeMap = { 
      only_sel: 1, 
      many_sel: 2, 
      yesorno: 3, 
      qna: 4 
    };
    
    const params = {
      qs_type: selectedQuestionType.value !== "all" 
        ? qsTypeMap[selectedQuestionType.value] 
        : null,
      difficulty: selectedDifficulty.value !== "all" 
        ? selectedDifficulty.value 
        : null,
      point_id: selectedFilterPoint.value !== "all" 
        ? selectedFilterPoint.value 
        : null
    };

    const response = await StufetchQuestions(params);
     if (response.data.status === 1) {
      questions.value = response.data.data.map(q => ({
        ...q,
        qs_star_id: q.qs_star_id, // 新增星标ID字段
        is_store: true
      }));
    }
  } catch (error) {
    console.error("获取试题失败:", error);
    ElMessage.error("获取试题失败，请稍后重试");
  }
};

    // 筛选的计算属性
    const filteredQuestions = computed(() => {
      return questions.value.filter(q => 
        q.qs_title.toLowerCase().includes(searchQuery.value.trim().toLowerCase())
      );
    });

    const searchQuestions = () => { 
      currentPage.value = 1; 
      fetchQuestionsData(); 
    };

    const paginatedData = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize;
      return filteredQuestions.value.slice(startIndex, startIndex + pageSize);
    });

    const totalPages = computed(() => Math.ceil(filteredQuestions.value.length / pageSize));

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    const getQuestionType = (type) => {
      return type === "only_sel" ? "单选" : type === "many_sel" ? "多选" : type === "yesorno" ? "判断" : type === "qna" ? "简答" : "未知类型";
    };

    const getDifficultyLabel = (difficulty) => {
      const labelMap = { "0": "简单", "1": "中等", "2": "困难" };
      return labelMap[difficulty] || "未知";
    };
  // 添加筛选方法
    const toggleFilterDirection = (directionId) => {
      selectedFilterDirection.value = directionId;
      selectedFilterPoint.value = "all";
      currentPage.value = 1;
      fetchQuestionsData();
    };

    const toggleFilterPoint = (pointId) => {
      selectedFilterPoint.value = pointId;
      currentPage.value = 1;
      fetchQuestionsData();
    };

    const toggleFilterQuestionType = (type) => {
      selectedQuestionType.value = type;
      currentPage.value = 1;
      fetchQuestionsData();
    };

    const toggleFilterDifficulty = (difficulty) => {
      selectedDifficulty.value = difficulty;
      currentPage.value = 1;
      fetchQuestionsData();
    };

    // 修改toggleFavorite方法
const toggleFavorite = async (question) => {
  if (question.is_store) {
    // 取消收藏（使用新的试题接口）
    try {
      const response = await removeQuestionFavorites(question.qs_star_id);
      if (response.data.status === 1) {
        question.is_store = false;
        ElMessage.success('取消收藏成功');
        fetchQuestionsData(); // 刷新列表
      }
    } catch (error) {
      ElMessage.error('取消收藏失败');
    }
  } else {
    // 添加收藏（使用新的试题接口）
    try {
      const response = await addQuestionFavorite({
        user_id: userId.value,
        qs_id: question.qs_id // 改为使用试题ID字段
      });
      if (response.data.status === 1) {
        question.is_store = true;
        question.qs_star_id = response.data.data.re_star_id; // 记录星标ID
        ElMessage.success('收藏成功');
      }
    } catch (error) {
      ElMessage.error('收藏失败');
    }
  }
};

    onMounted(() => {
      fetchDirections();
      fetchQuestionsData();
    });

    return {
      questions,
      currentPage,
      pageSize,
      searchQuery,
      selectedFilterDirection,
      selectedQuestionType,
      selectedDifficulty,
      directions,
      filteredQuestions,
      paginatedData,
      totalPages,
      handlePageChange,
      getQuestionType,
      getDifficultyLabel,
      searchQuestions,
       toggleFilterDirection,
      toggleFilterPoint,
      toggleFilterQuestionType,
      toggleFilterDifficulty,
      toggleFavorite
    };
  }
}
</script>

<style scoped>
.favorite-icon {
  position: absolute;
  top: 50%;
  left: 25%;
  transform: translateY(-50%);
  background-color: white;
  border-radius: 50%;
  padding: 6px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 10;
}

.favorite-icon img {
  width: 20px;
  height: 20px;
}

.table-row:hover .favorite-icon {
  opacity: 1;
}

.page-container {
  max-width: calc(100vw - 670px); /* 减去侧边栏宽度 */
  overflow-x: hidden;
}
/* 详情区域 */
.question-details {
  display: block;
}
.question-details summary {
  display: flex;
  align-items: center;
  cursor: pointer;
  list-style: none;
}
/* 合并两处 .question-options 定义 */
.question-options {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
  margin-top: 5px;
  padding: 10px 0 0 0;
}
.question-details[open] .question-options {
  max-height: 500px;
}
.question-details summary::before {
  content: '▶';
  margin-right: 8px;
}
.question-details[open] summary::before {
  content: '▼';
}

/* 顶部筛选 */
.top-filter {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10px;
}
.tab-bar {
  display: flex;
  background-color: white;
  padding: 10px;
}
.tab {
  padding: 10px 20px;
  cursor: pointer;
  transition: background 0.3s ease-in-out;
}
.tab.active {
  border-bottom: 2px solid #244382;
  color: #244382;
  font-weight: bold;
}
.search-container {
  display: flex;
  align-items: center;
  position: relative;
}
.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}
.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 20px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px;
}
.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}

/* 二级筛选 */
.secondary-filters {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  font-size: 14px;
}
.filter-group {
  display: flex;
  gap: 10px;
  align-items: center;
}
.filter-label {
  font-weight: bold;
  color: #666;
}
.secondary-filters span {
  padding: 5px 12px;
  cursor: pointer;
  border-radius: 4px;
  color: #333;
  transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}
.active-filter {
  color: #ffffff;
  background-color: #eaf4ff !important;
}
.secondary-filters span:hover:not(.active-filter) {
  background-color: #f0f0f0;
}

/* 题目表格 */
.question-table {
  width: 100%;
  border-collapse: collapse;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
  table-layout: fixed;
  font-size: 13px;
}
.question-table th,
.question-table td {
  border: 1px solid #ddd;
  padding: 12px 15px;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
.question-table th {
  background-color: #f7f7f7;
  color: #333;
}
.table-row:nth-child(even) {
  background-color: #f9f9f9;
}
.table-row:hover {
  background-color: #eef6ff;
}
.action-cell {
  position: relative;
  width: 100px;
}

/* 无结果提示 */
.no-results {
  text-align: center;
  padding: 20px;
}
</style>
